<template>
  <div>
    <el-card class="box-card">
      <el-row>
        <el-col :span="6">
          <el-upload
              class="upload-vhr"
              action="no"
              list-type="text"
              ref="uploadFile"
              accept="no"
              :auto-upload="false"
              :on-exceed="handleExceed"
              :http-request="customUpload"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :limit="1"
              :file-list="fileList">
            <el-input placeholder="请输入内容" v-model="fileName">
              <template slot="append">
                <el-button type="primary" icon="el-icon-folder-opened">
                  选择文件
                </el-button>
              </template>
            </el-input>
            <!--<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
          </el-upload>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" icon="el-icon-folder-opened" @click="submitUpload">
            提交
          </el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import {hex_md5} from "@/utils/md5.js";

export default {
  name: "EmpAdv",
  /*props: {
    afterUpload: {
      type: Function,
      default: null
    },
  },*/
  data() {
    return {
      file: "",
      fileList: [],
      fileName: "",
      url: {
        upload: "/file/upload",
        check: "/file/check"
      }
    };
  },
  methods: {
    submitUpload() {
      if (this.fileList == '') {
        this.$message.warning("请选择需要上传的文件！")
      } else {
        // 调用文件上传的钩子函数
        this.$refs.uploadFile.submit();
        this.fileList = []
      }
    },
    //自定义上传文件钩子，发送上传文件请求
    customUpload() {
      let file = this.file;
      let key = hex_md5(file.name + file.size + file.type);
      let suffix = file.name.substr(file.name.lastIndexOf(".") + 1).toLowerCase();
      // 文件分片
      let shardSize = 20 * 1024 * 1024; // 以20M为一个分片
      let shardIndex = 1; //分片索引, 1表示第一个分片
      let size = file.size;
      let shardTotal = Math.ceil(size / shardSize);

      let param = {
        "shardIndex": shardIndex,
        "shardSize": shardSize,
        "shardTotal": shardTotal,
        "fileUse": "C",
        "fileName": file.name,
        "suffix": suffix,
        "fileSize": size,
        "fileKey": key
      }
      this.check(param);
    },
    /**
     * 检查文件状态，是否已上传过？传到第几个分片？
     */
    check(param) {
      this.getRequest(this.url.check, {"fileKey": param.fileKey}).then(resp => {
        if (resp && resp.status) {
          let obj = resp.data;
          if (!obj) {
            param.shardIndex = 1;
            console.log("没有找到文件记录，从分片1开始上传");
            this.upload(param);
          } else if (obj.shardIndex === obj.shardTotal) {
            // 已上传分片 = 分片总数，说明已全部上传完，不需要再上传
            this.$message.success("文件极速秒传成功！");
          } else {
            param.shardIndex = obj.shardIndex + 1;
            console.log("找到文件记录，从分片" + param.shardIndex + "开始上传");
            this.upload(param);
          }
        } else {
          this.$message.error("文件上传失败");
        }
      })
    },
    upload(param) {
      let shardIndex = param.shardIndex;
      let shardTotal = param.shardTotal;
      let shardSize = param.shardSize;
      let fileShard = this.getFileShard(shardIndex, shardSize);
      // 将图片转为 base64 进行传输
      let fileReader = new FileReader();
      fileReader.onload = (e => {
        let base64 = e.target.result;
        param.shard = base64;

        this.postRequest(this.url.upload, param).then(resp => {
          if (resp && resp.status) {
            this.fileName = "";
            this.fileList = []
          } else {
            this.$message.error(resp.msg)
          }
          let respData = resp.data
          if (shardIndex < shardTotal) {
            // 上传下一个分片
            param.shardIndex = param.shardIndex + 1;
            this.upload(param);
          } else {
            this.$message.success("上传成功")
          }

        })
      })
      fileReader.readAsDataURL(fileShard);
    },
    getFileShard(shardIndex, shardSize) {
      let file = this.file;
      // 当前分片起始位置
      let start = (shardIndex - 1) * shardSize;
      //当前分片结束位置
      let end = Math.min(file.size, start + shardSize);
      let fileShard = file.slice(start, end);
      return fileShard;
    },
    handleRemove(file, fileList) {
      // 删除上传文件
      this.fileName = "";
      this.fileList = []
    },
    handleChange(file, fileList) {
      // 文件状态钩子，选择文件时触发
      this.fileList = fileList;
      this.fileName = file.name;
      this.file = this.fileList[0].raw;

    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
  }
}
</script>

<style scoped>

</style>
